<template>
  <div>
    <Nav>地图详情</Nav>
    <van-search
          shape="round"
          v-model="value"
          placeholder="请输入搜索关键词"
        />
    <div class="notice">

    <ul class="noticeList">
      <li class="notice-item"  v-for="item in tipList" :key="item.id" @click="goHome(item)">
       <span class="txt-t">{{ item.name }}</span>
        <van-icon class="txt-r" name="arrow" />
      </li>
    </ul>
    </div>

    <div class="bottom">
        <p>当前位置</p>
    <div id="container"></div>

    </div>

  </div>
</template>

<script>
import { ref, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import AMap from 'AMap'
export default {
  name: 'MapApi',
  setup () {
    const router = useRouter()
    const store = useStore()
    const value = ref('')
    const tipList = ref('')
    const city = ref('')
    const cityDetail = store.state.cityDetail
    // 初始化
    onMounted(() => {
      init()
    })
    function init () {
      if (cityDetail) {
        const map = new AMap.Map('container', {
          zoom: 18, // 级别
          center: [cityDetail.location.lng, cityDetail.location.lat] // 中心点坐标
        })
        const marker = new AMap.Marker({
          position: [cityDetail.location.lng, cityDetail.location.lat] // 位置
        })
        marker.setLabel({
          direction: 'right',
          offset: new AMap.Pixel(10, 0), // 设置文本标注偏移量
          content: cityDetail.name // 设置文本标注内容
        })
        map.add(marker) // 添加到地图
      } else {
        const map = new AMap.Map('container', {
          zoom: 7 // 级别
        })
        const marker = new AMap.Marker({
          position: [116.39, 39.9]// 位置
        })
        map.add(marker)// 添加到地图
      }
    }

    watch(() => value.value, (newValue, oldValue) => {
      AMap.plugin('AMap.AutoComplete', function () {
        const autoOptions = {
          // city 限定城市，默认全国
          city: 'cite.vale'
        }
        // 实例化AutoComplete
        const autoComplete = new AMap.AutoComplete(autoOptions)
        // 根据关键字进行搜索
        autoComplete.search(value.value, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          console.log(result)
          tipList.value = result.tips
        })
      })
    })
    const goHome = (val) => {
      store.commit('reCity', val)
      router.push('/')
    }

    return { value, tipList, city, AMap, goHome }
  }
}
</script>

<style lang="scss" scoped>
@import "./scss/index.scss";
</style>
